<template>
  <div class="dashboard">
    <!-- 审批概况 -->
    <div class="overview-row">
      <el-card
        v-for="item in overviewList"
        :key="item.label"
        class="overview-card"
        :body-style="{ padding: '20px' }"
        v-loading="loading.overview"
      >
        <div class="overview-label">{{ item.label }}</div>
        <div class="overview-value">{{ item.value || 0 }}</div>
        <el-icon :size="32" class="overview-icon" :style="{ background: item.bg }">
          <component :is="item.icon" />
        </el-icon>
      </el-card>
    </div>

    <!-- 月度审批趋势 -->
    <el-card class="chart-card" v-loading="loading.monthTrend">
      <div class="chart-title-row">
        <span class="chart-title">月度审批趋势</span>
        <el-select
          v-model="selectedYear"
          class="year-select"
          size="small"
          style="width: 120px"
          @change="fetchMonthTrend"
        >
          <el-option v-for="year in yearList" :key="year" :label="year + '年'" :value="year" />
        </el-select>
      </div>
      <v-chart :option="lineOption" autoresize style="width: 100%; height: 320px" />
    </el-card>

    <!-- 各部门审批数量 -->
    <el-card class="chart-card" v-loading="loading.deptCount">
      <div class="chart-title">各部门审批数量</div>
      <v-chart :option="deptBarOption" autoresize style="width: 100%; height: 320px" />
    </el-card>

    <!-- 各类型审批数量 -->
    <el-card class="chart-card" v-loading="loading.typeCount">
      <div class="chart-title">各类型审批数量</div>
      <v-chart :option="typeBarOption" autoresize style="width: 100%; height: 320px" />
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { Document, Folder, CircleCheck, CircleClose, Delete } from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import VChart from 'vue-echarts'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, LegendComponent, TitleComponent } from 'echarts/components'
import {
  getApprovalCount,
  getMonthApprovalCountByYear,
  getDeptApprovalCount,
  getTypeApprovalCount
} from '@/api/approval/analysis/overview.js'
import { ElMessage } from 'element-plus'

use([CanvasRenderer, LineChart, BarChart, GridComponent, TooltipComponent, LegendComponent, TitleComponent])

// 数据状态
const overviewList = ref([
  { label: '全部审批', value: 0, icon: Document, bg: '#fff7e6' },
  { label: '审批中', value: 0, icon: Folder, bg: '#f5f7ff' },
  { label: '审批通过', value: 0, icon: CircleCheck, bg: '#e6fff7' },
  { label: '审批拒绝', value: 0, icon: CircleClose, bg: '#e6f7ff' }
  // { label: '审批撤销', value: 0, icon: Delete, bg: '#fff0f0' }
])

const yearList = [2025, 2024, 2023, 2022, 2021]
const selectedYear = ref(2025)
const loading = ref({ overview: false, monthTrend: false, deptCount: false, typeCount: false })

const monthApprovalCount = ref([])
const deptApproval = ref([])
const deptApprovalDeptName = ref([])
const deptApprovalApprovalCount = ref([])
const typeApprovalArray = ref([])
const typeApprovalCountArray = ref([])

// 初始化数据
onMounted(() => {
  fetchOverviewData()
  fetchMonthTrend()
  fetchDeptCount()
  fetchTypeCount()
})

// 获取审批概况数据
async function fetchOverviewData() {
  loading.value.overview = true
  try {
    const [all, pending, approved, rejected] = await Promise.all([
      getApprovalCount(),
      getApprovalCount({ status: 'pending' }),
      getApprovalCount({ status: 'approved' }),
      getApprovalCount({ status: 'rejected' })
    ])
    overviewList.value[0].value = all.data || 0
    overviewList.value[1].value = pending.data || 0
    overviewList.value[2].value = approved.data || 0
    overviewList.value[3].value = rejected.data || 0
  } catch (error) {
    ElMessage.error('获取审批概况数据失败')
    console.error(error)
    overviewList.value.forEach(item => (item.value = 0)) // 失败时重置为0
  } finally {
    loading.value.overview = false
  }
}

// 获取月度审批趋势数据
async function fetchMonthTrend() {
  loading.value.monthTrend = true
  try {
    const res = await getMonthApprovalCountByYear({ year: selectedYear.value })
    monthApprovalCount.value = res.rows.map(item => item.count || 0)
  } catch (error) {
    ElMessage.error('获取月度审批趋势数据失败')
    monthApprovalCount.value = Array(12).fill(0) // 失败时填充默认值
  } finally {
    loading.value.monthTrend = false
  }
}

// 获取各部门审批数量
async function fetchDeptCount() {
  loading.value.deptCount = true
  try {
    const res = await getDeptApprovalCount()
    deptApproval.value = res.rows
    deptApprovalDeptName.value = deptApproval.value.map(item => item.deptName || '未知部门')
    deptApprovalApprovalCount.value = deptApproval.value.map(item => item.approvalCount || 0)
  } catch (error) {
    ElMessage.error('获取各部门审批数量失败')
    deptApprovalDeptName.value = ['数据缺失']
    deptApprovalApprovalCount.value = [0]
  } finally {
    loading.value.deptCount = false
  }
}

// 获取各类型审批数量
async function fetchTypeCount() {
  loading.value.typeCount = true
  try {
    const res = await getTypeApprovalCount()
    typeApprovalArray.value = res.rows.map(item => item.typeName || '未知类型')
    typeApprovalCountArray.value = res.rows.map(item => item.approvalCount || 0)
  } catch (error) {
    ElMessage.error('获取各类型审批数量失败')
    typeApprovalArray.value = ['数据缺失']
    typeApprovalCountArray.value = [0]
  } finally {
    loading.value.typeCount = false
  }
}

// 监听年份变化
watch(selectedYear, fetchMonthTrend)

// 月度审批趋势折线图
const lineOption = computed(() => ({
  tooltip: { trigger: 'axis' },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  },
  yAxis: { type: 'value', min: 0 },
  series: [{
    name: '审批量',
    data: monthApprovalCount.value,
    type: 'line',
    smooth: true,
    symbol: 'circle',
    symbolSize: 10,
    lineStyle: { width: 3, color: '#3a7afe' },
    itemStyle: { color: '#3a7afe' },
    areaStyle: { color: 'rgba(58,122,254,0.08)' },
    label: { show: true, position: 'top' }
  }]
}))

// 各部门审批数量柱状图
const deptBarOption = computed(() => ({
  tooltip: { trigger: 'axis' },
  xAxis: {
    type: 'category',
    data: deptApprovalDeptName.value,
    axisLabel: { rotate: 45 } // 部门名称过长时旋转
  },
  yAxis: { type: 'value', min: 0 },
  series: [{
    name: '审批量',
    data: deptApprovalApprovalCount.value,
    type: 'bar',
    barWidth: 24,
    itemStyle: { color: '#3a7afe' },
    label: { show: true, position: 'top' }
  }]
}))

// 各类型审批数量柱状图
const typeBarOption = computed(() => ({
  tooltip: { trigger: 'axis' },
  xAxis: {
    type: 'category',
    data: typeApprovalArray.value,
    axisLabel: { rotate: 45 } // 类型名称过长时旋转
  },
  yAxis: { type: 'value', min: 0 },
  series: [{
    name: '审批量',
    data: typeApprovalCountArray.value,
    type: 'bar',
    barWidth: 24,
    itemStyle: { color: '#36cfc9' },
    label: { show: true, position: 'top' }
  }]
}))
</script>

<style scoped>
.dashboard {
  background: #f6f7fb;
  min-height: 100vh;
  padding: 24px;
}

.overview-row {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
  flex-wrap: wrap; /* 适配小屏幕 */
}

.overview-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  min-width: 180px;
  min-height: 110px;
  position: relative;
  transition: transform 0.2s;
}

.overview-card:hover {
  transform: scale(1.02); /* 鼠标悬停放大 */
}

.overview-label {
  font-size: 16px;
  color: #888;
  margin-bottom: 8px;
}

.overview-value {
  font-size: 32px;
  font-weight: bold;
  color: #222;
}

.overview-icon {
  position: absolute;
  right: 24px;
  top: 24px;
  border-radius: 50%;
  padding: 8px;
  transition: transform 0.2s;
}

.overview-icon:hover {
  transform: rotate(15deg); /* 图标悬停旋转 */
}

.chart-card {
  margin-bottom: 24px;
}

.chart-title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.chart-title {
  font-size: 18px;
  font-weight: 600;
}

.year-select {
  min-width: 120px;
}

@media (max-width: 768px) {
  .overview-card {
    min-width: 150px;
  }
  .chart-card {
    height: 280px;
  }
}
</style>